package com.lovo.service.impl;

import com.lovo.dao.UserDAO;
import com.lovo.model.*;
import com.lovo.model.InvoiceDO;
import com.lovo.model.RoleDO;
import com.lovo.model.UserDO;
import com.lovo.model.dto.InvoiceDTO;
import com.lovo.model.dto.RoleDTO;
import com.lovo.model.dto.UserDTO;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResultCode;
import com.lovo.service.UserService;
import org.apache.tomcat.jni.Time;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.management.relation.Role;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Resource
    private UserDAO userDAO;

    @Override
    public UserDO findByID(Integer userId) {
        return userDAO.findById(userId).orElse(null);
    }

    @Override
    public List findAll() {
        List<UserDO> userList = userDAO.findAll();
        List userDTOList = new ArrayList();
        for (UserDO userDO:userList) {
            UserDTO userDTO = new UserDTO(userDO.getUserId(),userDO.getPhone());
            List<RoleDO> roleList = userDO.getRoleList();
            for(RoleDO roleDO : roleList){
                userDTO.getRoleList().add(new RoleDTO(roleDO.getRoleId(),roleDO.getRoleName()));
            }
            List<InvoiceDO> invoiceList = userDO.getInvoiceList();
            for(InvoiceDO invoiceDO : invoiceList){
                userDTO.getInvoiceList().add(new InvoiceDTO(invoiceDO.getId(),invoiceDO.getAmount(),invoiceDO.getUrl()));
            }
            userDTOList.add(userDTO);
        }
        return userDTOList;
    }

    @Override
    public void save(UserDO userDO) {
        userDAO.save(userDO);
    }

    @Override
    public void update(UserDO userDO) throws InterruptedException {

        userDAO.save(userDO);
        Thread.sleep(15000);
    }

    @Override
    public void delete(UserDO userDO) {
        userDAO.delete(userDO);
    }

    @Override
    public UserDTO validate(String phone, String pwd) throws GlobalHandleException {
        UserDO userDO = userDAO.findByPhoneAndPwd(phone,pwd);
        UserDTO userDTO = null;
        if(userDO != null){
            userDTO = new UserDTO();
            BeanUtils.copyProperties(userDO,userDTO,"invoiceList","roleList");
        }else{
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }
        return userDTO;
    }

    @Override
    public List findCondition(String phone) {
        return userDAO.findCondition(phone);
    }

    @Override
    public void deleteByPhone(String phone) {
        userDAO.deleteByPhone(phone);
    }
}
